use std::fs;

const ICON_MEM: &str = " ";

pub struct Memory {
    icon: String,
    total: usize,
    available: usize,
    percent: usize,
}

impl Memory {
    pub fn new() -> Self {
        Memory {
            icon: String::from(ICON_MEM),
            total: 1,
            available: 0,
            percent: 0,
        }
    }

    /**
     * 获取内存展示信息
     */
    pub fn display(&mut self) -> String {
        self.update();
        format!("{}{}%", self.icon, self.percent)
    }

    /**
     * 更新内存信息
     */
    fn update(&mut self) {
        let result = fs::read_to_string("/proc/meminfo");
        if let Ok(content) = result {
            for line in content.lines() {
                if line.contains("MemTotal:") {
                    self.total = Memory::parse_string_num(line);
                } else if line.contains("MemAvailable:") {
                    self.available = Memory::parse_string_num(line);
                    break;
                }
            }
            self.percent = (self.total - self.available) * 100 / self.total;
        } else {
            eprintln!("update mem info faild!");
        }
    }

    /**
     * 解析字符串中的数字
     */
    fn parse_string_num(line: &str) -> usize {
        let mut num: usize = 0;
        for c in line.chars() {
            if c >= '0' && c <= '9' {
                num = num * 10 + c as usize - 48;
            }
        }
        num
    }
}
